<template>

  <div>
    <Model :ref="modelRef" :title="title" :footer="true" :width="width" :mask="true" @handlerClick="handlerClick">
      <div class="right-radio">
        <el-radio-group v-model="radioXML" size="small"  @change="handleRadioChange">
          <el-radio label="1" border>表单</el-radio>
          <el-radio label="2" border>流程</el-radio>
        </el-radio-group>
      </div>
      <div class="cont">
        <div class="cont-bcform" v-show="radioXML === '1'">
          <bcForm :form="formUpload" labelWidth="172px" ref="bcForm" @handleChange=handleChange :flex="true"></bcForm>
        </div>
      </div>
      <div class="cont-bcform" v-show="radioXML === '2'">
        <Bpmn-viewer :flowData="flowData" :procInsId="toString(dataInfo.id)"/>
      </div>
    </Model>
  </div>
</template>

<script>
import Model from '@/components/PerCom/model.vue'
import commonUtils from "@/utils/commonUtils";
import BpmnViewer from "@/components/Process/viewer/index.vue";
import BcForm from '@/components/PerCom/bcForm'
import {processApi} from "@/api/modules";

export default {
  name: "PestDiseaseLogEdit",
  components: {
    BpmnViewer,
    Model,
    BcForm
  },
  data() {
    return {
      title: '',
      modelRef: commonUtils.createHash(),
      width: '1280',
      editType: '',
      flowData: {},
      dataInfo: {id: ""},
      radioXML: '1',
      formUpload: [],
      result: {}
    }
  },
  methods: {
    // 监听 radio 切换事件
    handleRadioChange(val) {
      console.log('Radio 切换到:', val);

      if (val === '2') {
        // 切换到流程图时的处理
        this.$nextTick(() => {
          // 确保 DOM 更新完成后执行
          // if (this.$refs.bpmnViewer) {
          //   // 如果需要触发 BPMN Viewer 重新渲染
          //   this.$refs.bpmnViewer.renderDiagram && this.$refs.bpmnViewer.renderDiagram();
          // }
          this.loadAndDisplayData()
        });
      } else if (val === '1') {
        // 切换到表单时的处理
        console.log('切换到表单视图');
      }
    },
    // 获取流程数据
    async getProcessMap() {
      this.loading = true;
      this.error = null;

      try {
        const result = await processApi.getProcessMap();
        this.processData = result.data;
        return result.data;
      } catch (err) {
        this.error = err.message || '数据加载失败';
        console.error('加载流程数据失败:', err);
        throw err;
      } finally {
        this.loading = false;
      }
    },
    // 加载并显示数据
    async loadAndDisplayData() {
      try {
        // 获取流程数据
        const data = await this.getProcessMap();

        // 检查是否返回数据并渲染
        if (data) {
          console.log('接口返回数据:', data);
          this.flowData = data;
          console.log('流程数据:', this.flowData)
          this.dataInfo.id = "162511"
        } else {
          // 使用默认数据
          this.useDefaultData();
        }
      } catch (err) {
        console.error('加载数据失败:', err);
        // 出错时使用默认数据
        this.useDefaultData();
      }
    },
    useDefaultData() {
      const defaultFlowData = {
        nodeData: [
          {key: 'start_event', completed: true},
          {key: 'Flow_0bbh4bn', completed: true},
          {key: 'Flow_15zl636', completed: true},
          {key: 'Activity_submit', completed: false}
        ],
        "xmlData": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<definitions xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:bpmndi=\"http://www.omg.org/spec/BPMN/20100524/DI\" xmlns:omgdc=\"http://www.omg.org/spec/DD/20100524/DC\" xmlns:bioc=\"http://bpmn.io/schema/bpmn/biocolor/1.0\" xmlns:flowable=\"http://flowable.org/bpmn\" xmlns:di=\"http://www.omg.org/spec/DD/20100524/DI\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" targetNamespace=\"http://www.flowable.org/processdef\">\n  <process id=\"flow_pests_diseases\" name=\"审核流程\">\n    <startEvent id=\"start_event\" name=\"开始\">\n      <outgoing>Flow_0bbh4bn</outgoing>\n    </startEvent>\n    <userTask id=\"Activity_approval\" name=\"审核\" flowable:assignee=\"117\" flowable:userType=\"assignee\" flowable:dataType=\"fixed\">\n      <incoming>Flow_15zl636</incoming>\n      <outgoing>Flow_0kmf5fo</outgoing>\n    </userTask>\n    <endEvent id=\"Event_1i68fw9\">\n      <incoming>Flow_0kmf5fo</incoming>\n    </endEvent>\n    <sequenceFlow id=\"Flow_0kmf5fo\" sourceRef=\"Activity_approval\" targetRef=\"Event_1i68fw9\" />\n    <userTask id=\"Activity_submit\" name=\"提交\" flowable:assignee=\"118\" flowable:userType=\"assignee\" flowable:dataType=\"fixed\">\n      <incoming>Flow_0bbh4bn</incoming>\n      <outgoing>Flow_15zl636</outgoing>\n    </userTask>\n    <sequenceFlow id=\"Flow_0bbh4bn\" sourceRef=\"start_event\" targetRef=\"Activity_submit\" />\n    <sequenceFlow id=\"Flow_15zl636\" sourceRef=\"Activity_submit\" targetRef=\"Activity_approval\" />\n  </process>\n  <bpmndi:BPMNDiagram id=\"BPMNDiagram_flow\">\n    <bpmndi:BPMNPlane id=\"BPMNPlane_flow\" bpmnElement=\"flow_pests_diseases\">\n      <bpmndi:BPMNShape id=\"BPMNShape_start_event\" bpmnElement=\"start_event\" bioc:stroke=\"\">\n        <omgdc:Bounds x=\"25\" y=\"155\" width=\"30\" height=\"30\" />\n        <bpmndi:BPMNLabel>\n          <omgdc:Bounds x=\"28\" y=\"192\" width=\"22\" height=\"14\" />\n        </bpmndi:BPMNLabel>\n      </bpmndi:BPMNShape>\n      <bpmndi:BPMNShape id=\"Activity_1bfkgvr_di\" bpmnElement=\"Activity_approval\">\n        <omgdc:Bounds x=\"255\" y=\"240\" width=\"100\" height=\"80\" />\n        <bpmndi:BPMNLabel />\n      </bpmndi:BPMNShape>\n      <bpmndi:BPMNShape id=\"Event_1i68fw9_di\" bpmnElement=\"Event_1i68fw9\">\n        <omgdc:Bounds x=\"502\" y=\"197\" width=\"36\" height=\"36\" />\n      </bpmndi:BPMNShape>\n      <bpmndi:BPMNShape id=\"Activity_169fhvp_di\" bpmnElement=\"Activity_submit\">\n        <omgdc:Bounds x=\"255\" y=\"80\" width=\"100\" height=\"80\" />\n        <bpmndi:BPMNLabel />\n      </bpmndi:BPMNShape>\n      <bpmndi:BPMNEdge id=\"Flow_0kmf5fo_di\" bpmnElement=\"Flow_0kmf5fo\">\n        <di:waypoint x=\"355\" y=\"280\" />\n        <di:waypoint x=\"471\" y=\"280\" />\n        <di:waypoint x=\"471\" y=\"215\" />\n        <di:waypoint x=\"502\" y=\"215\" />\n      </bpmndi:BPMNEdge>\n      <bpmndi:BPMNEdge id=\"Flow_0bbh4bn_di\" bpmnElement=\"Flow_0bbh4bn\">\n        <di:waypoint x=\"55\" y=\"170\" />\n        <di:waypoint x=\"155\" y=\"170\" />\n        <di:waypoint x=\"155\" y=\"120\" />\n        <di:waypoint x=\"255\" y=\"120\" />\n      </bpmndi:BPMNEdge>\n      <bpmndi:BPMNEdge id=\"Flow_15zl636_di\" bpmnElement=\"Flow_15zl636\">\n        <di:waypoint x=\"305\" y=\"160\" />\n        <di:waypoint x=\"305\" y=\"240\" />\n      </bpmndi:BPMNEdge>\n    </bpmndi:BPMNPlane>\n  </bpmndi:BPMNDiagram>\n</definitions>\n"
      };
      this.flowData = defaultFlowData
      this.dataInfo.id = "162511"
    },


    handlerClick(val) { //保存数据
      this.loadAndDisplayData()
      if (val == 'confirm' && !this.editType) {
        const processObj = this.$refs.approvalRecordRef.processObj;
        console.log(processObj, '000000000000000')
        let obj = {}
        obj.comment = processObj.textarea;
        let tagReportArr = processObj.tagReport.map((item) => item.userId);
        if (tagReportArr && tagReportArr.length > 0) {
          obj.signUsers = tagReportArr.join(',');
        } else {
          obj.signUsers = '';
        }
        let tagMakeCopeArr = processObj.tagMakeCope.map((item) => item.userId);
        if (tagMakeCopeArr && tagMakeCopeArr.length > 0) {
          obj.copyToUsers = tagMakeCopeArr.join(',');
        } else {
          obj.copyToUsers = '';
        }
        obj.id = this.dataInfo.id;
        if (processObj.upload.fileList && processObj.upload.fileList.length > 0) {
          const imgData = processObj.upload.fileList;
          const formData = new FormData();
          obj.radioVal = processObj.radioVal;
          imgData.forEach(file => {
            formData.append('files', file.raw);
          })
          this.uploadImgFun(formData, obj);
        } else {
          obj.files = '';
          if (this.dataInfo.processStatus === 1 || this.dataInfo.processStatus === 3) {
            this.pestsDiseasesFlowSubmitFun(obj)
            return
          }
          if (processObj.radioVal == 1) {//同意
            this.pestsDiseasesFlowApprovedFun(obj)
          } else if (processObj.radioVal == 2) {//退回
            this.pestsDiseasesFlowBackFun(obj)
          } else if (processObj.radioVal == 3) {//终止
            this.pestsDiseasesFlowStopFun(obj)
          }
        }
      } else if (val == 'confirm' && this.editType) {
        this.$refs.bcForm.validate((type, data) => {
          if (type) {
            this.result = {
              ...this.result,
              ...data
            };
            const fileData = this.hortFileList.filter(item => !item.id);
            if (fileData && fileData.length > 0) {
              const formData = new FormData();
              fileData.forEach(file => {
                formData.append('files', file.raw);
              })
              this.uploadFileMuFun(formData, 'files');
            } else {
              this.pestsDiseasesFlowUpdateFun();
            }
          }
        })
      }
    },
    open(data, editType) {
      console.log(data, 'data')
      this.editType = editType;
      this.dataInfo = data;
      this.radioXML = '1';
      if (data.fileList && data.fileList.length > 0) {
        this.hortFileList = this.dataInfo.fileList;
      }
      if (this.dataInfo.processStatus && this.dataInfo.processStatus != 1) {
        this.xmlDataClick();
        this.getCollaborativeRecord();
      }
      if (editType && editType == 'edit') {
        this.disabledUpload = false;
        this.width = '868'
      } else {
        this.width = '1280'
        this.disabledUpload = true;
      }
      this.title = '病虫害日志';
      this.formInit(this.dataInfo);
      this.$refs[this.modelRef].show();
    },
    formInit(data) {
      let vm = this
      this.formUpload = [{
        type: 'input',
        props: 'jdName',
        label: '基地名称',
        disabled: true,
        defaultValue: data && data.jdName,
        rules: {
          required: true,
          message: '请输入基地名称',
          trigger: 'change'
        }
      },
        {
          type: 'input',
          props: 'areaName',
          label: '区域名称',
          disabled: true,
          defaultValue: data && data.areaName,
          rules: {
            required: true,
            message: '请输入区域名称',
            trigger: 'change'
          }
        },
        {
          type: 'input',
          props: 'rowNumber',
          label: '行编号',
          disabled: true,
          defaultValue: data && data.rowNumber,
          rules: {
            required: true,
            message: '请输入行编号',
            trigger: 'change'
          }
        },
        {
          type: 'input',
          props: 'pdType',
          label: '病虫害类型',
          disabled: true,
          defaultValue: data && data.pdType,
          rules: {
            required: true,
            message: '请输入工人姓名',
            trigger: 'change'
          }
        },
        {
          type: 'input',
          props: 'recorder',
          label: '记录人',
          disabled: true,
          defaultValue: data && data.recorder,
          rules: {
            validator: vm.growthCycle,
            trigger: 'change'
          }
        },
        {
          type: 'input',
          props: 'recordTime',
          label: '记录日期',
          disabled: true,
          defaultValue: data && data.recordTime,
          rules: {
            required: true,
            message: '请输入生产区数量(总行)',
            trigger: 'change'
          }
        },
        {
          type: 'textarea',
          props: 'description',
          label: '问题描述',
          disabled: vm.disabledUpload,
          defaultValue: data && data.description,
          rules: {
            required: true,
            message: '请输入问题描述',
            trigger: 'change'
          }
        },
        {
          type: 'input1',
          props: 'empty',
          label: ''
        },
        {
          type: 'textarea',
          props: 'comment',
          label: '处置意见',
          disabled: vm.disabledUpload,
          defaultValue: data && data.comment,
          rules: {
            required: true,
            message: '请输入处置意见',
            trigger: 'change'
          }
        },
        {
          type: 'input1',
          props: 'empty',
          label: ''
        },
        {
          type: 'textarea',
          props: 'remark',
          label: '备注',
          disabled: vm.disabledUpload,
          defaultValue: data && data.remark
        }
      ]
      setTimeout(() => {
        // this.uploadTypeList = enumeration.getProprDicByType('upload_type');
        // console.log(this.uploadTypeList, '00000000000000')
        this.$refs.bcForm.formInit();
      }, 0)
    },
    handleChange(result, data) {
      this.result = {
        ...this.result,
        ...result
      };
    },
  },
  mounted() {
    this.loadAndDisplayData()
  }
}

</script>


<style lang="scss" scoped>
.cont {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  // max-height: 680px;
  justify-content: space-between;
  .right-radio{
    position: absolute;
    left: 12px;
    top: 128px;
    z-index: 99;
    ::v-deep .el-radio-group {
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      align-items: baseline;
      height: 78px;
    }
  }
}

.cont-bcform {
  width: 868px;
  height: 100%;

  .cont-upload {
    width: 100%;
    // height: 180px;
    display: flex;
    flex-direction: column;

    .cont-img {
      // width: 100%;
      flex-wrap: nowrap;
      height: 88px;
      display: flex;
      padding: 14px 0;
      margin-right: 24px;
      align-items: center;
      padding-left: 116px;

      ::v-deep .el-upload--picture-card {
        width: 88px;
        height: 88px;
        line-height: 86px;
      }

      ::v-deep .el-upload-list__item {
        width: 88px;
        height: 88px;
      }
    }
  }

  ::v-deep .el-textarea {
    width: 638px;
    /* 自定义宽度 */
  }

  .cont1 {
    // width: 100%;
    height: 88px;
    display: flex;
    padding: 14px 0;
    margin-right: 24px;
    align-items: center;
    margin-left: 60px;

    p {
      width: 128px;
      font-size: 14px;
      text-align: right;
      color: #606266;
      flex-shrink: 0;
      font-weight: 600;
      padding-right: 12px;
    }

    &>div {
      overflow: hidden;
    }
  }

  .cont-btns {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    padding-right: 104px;
  }
}

.cont-pro {
  width: 368px;
  // height: 100%;
  height: 680px;
  display: flex;
  overflow-y: auto;
}

</style>
